﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Collections;
using System.ComponentModel;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Net.Mail;
using System.Net;
using System.Threading;
using System.Collections.Generic;


namespace VatLid
{
    public class DAL
    {
        private static string ConnStr = SecureConnection.GetCnxString("ConnStr");
        private static string ConnSync = SecureConnection.GetCnxString("ConnSync");
        private static string ConnReport = SecureConnection.GetCnxString("ConnStrReport");
        private static string ConnDUTD = SecureConnection.GetCnxString("ConnStrDUTD");
        private static string ConnReportSMS = SecureConnection.GetCnxString("ConnStrReportSMS");
        private static string ConnStrStore = SecureConnection.GetCnxString("ConnStrStore");

        public static void FillDataToDropdownList(string ConnString, DropDownList ddlList, string SQL, string FieldList, string DefaultText)
        {
            string[] arrField;
            arrField = FieldList.Split(',');
            DataSet ds = new DataSet();
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnString);
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                da.Fill(ds, "table");
                ddlList.DataSourceID = null;
                ddlList.DataSource = ds;
                ddlList.DataMember = "table";
                ddlList.DataValueField = arrField[0];// Field1;
                ddlList.DataTextField = arrField[1];// Field2;			

                ddlList.AppendDataBoundItems = true;
                ddlList.Items.Add(new ListItem(DefaultText, "0"));
                ddlList.SelectedValue = "0";
                ddlList.DataBind();
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }
        public static DataView CreateDataView2(string SQL)
        {
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(getConnectionString2());
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt.DefaultView;
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
                return null;
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }
        
        public static void ExecuteQuery2(string SQL)
        {
            ExecuteQuery(getConnectionString2(), SQL);
        }

        public static string getCategoryName(string id)
        {
            String sql = "select CategoryName from Categories where ID=" + id;
            String[] dl = VatLid.DAL.GetDataReaderToStringList(sql);
            if (dl != null)
            {
                return dl[0];
            }
            return "";
        }

        public static void ExecuteQuery(string connString, string SQL)
        {
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(connString);
                conn.Open();
                SqlCommand cmd = new SqlCommand(SQL, conn);
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }
        public static DataTable CreateDataView(string SQL, string connectStr)
        {
            DataTable table = null;
            using (SqlConnection conn = new SqlConnection(connectStr))
            using (SqlCommand cmd = new SqlCommand(SQL, conn))
            {
                try
                {
                    conn.Open();
                    cmd.CommandTimeout = 10;
                    using (SqlDataAdapter reader = new SqlDataAdapter(cmd))
                    {
                        try
                        {
                            table = new DataTable();
                            reader.Fill(table);
                        }
                        catch
                        {
                            table = null;
                        }
                    }
                }
                catch
                {
                    table = null;
                }
                finally
                {
                    if (conn != null)
                        conn.Close();
                    conn.Dispose();
                }
            }
            return table;
        }
        
        
        public static void FillDataToDropdownList2(DropDownList ddlList, string TableName, string FieldList)
        {
            string SQL = "SELECT " + FieldList + " FROM " + TableName;
            string[] arrField;
            arrField = FieldList.Split(',');
            DataSet ds = new DataSet();
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(getConnectionString2());
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                da.Fill(ds, TableName);
                ddlList.DataSourceID = null;
                ddlList.DataSource = ds;
                ddlList.DataMember = TableName;
                ddlList.DataValueField = arrField[0];// Field1;
                ddlList.DataTextField = arrField[1];// Field2;			
                ddlList.DataBind();
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }
        public static string getConnectionString2()
        {
            return SecureConnection.GetCnxString("ConnStr2");
        }

        public static string getConnectionDUTD()
        {
            return SecureConnection.GetCnxString("ConnDUTD");
        }

        private static Random rnd = new Random();

        #region "Exception"

        public static string getConnectionString()
        {
            return ConnStr;
        }

        public static string getConnectionStringReport()
        {
            return ConnReport;
        }

        public static string getConnectionStringReportSMS()
        {
            return ConnReportSMS;
        }

        public static string getConnStrStore()
        {
            return ConnStrStore;
        }

        public static string getConnectionStringSync()
        {
            return ConnSync;
        }

        public static void ExceptionProcess(Exception e)
        {
            
        }

        public static void ExceptionNoneProcess(Exception e)
        {
            
        }
        
        public static void EmailExceptionProcess(Exception e)
        {

        }

        #endregion

        #region "Common functions"

        //public static string ConvertVietnameseCharacterToEN(string sCharacter)
        //{
        //    string sTemplate = "ĂẮẰẲẴẶăắằẳẵặÂẤẦẨẪẬâấầẩẫậÁÀẢÃẠáàảãạÔỐỒỔỖỘôốồổỗộƠỚỜỞỠỢơớờởỡợÓÒỎÕỌóòỏõọĐđÊẾỀỂỄỆêếềểễệÉÈẺẼẸéèẻẽẹƯỨỪỬỮỰưứừửữựÚÙỦŨỤúùủũụÍÌỈĨỊíìỉĩịÝỲỶỸỴýỳỷỹỵ";
        //    string sReplate = "AAAAAAaaaaaaAAAAAAaaaaaaAAAAAaaaaaOOOOOOooooooOOOOOOooooooOOOOOoooooDdEEEEEEeeeeeeEEEEEeeeeeUUUUUUuuuuuuUUUUUuuuuuIIIIIiiiiiYYYYYyyyyy";
        //    char[] arrChar = sTemplate.ToCharArray();
        //    char[] arrReChar = sReplate.ToCharArray();
        //    string sResult = "";//sCharacter;
        //    char digit;

        //    for (int ch = 0; ch < sCharacter.Length; ch++)
        //    {
        //        digit = Convert.ToChar(sCharacter.Substring(ch, 1));//arrChar[ch].ToString();;
        //        for (int i = 0; i < arrChar.Length; i++)
        //            if (digit.Equals(arrChar[i]))
        //                digit = arrReChar[i];
        //        sResult += digit;
        //    }

        //    return sResult.Replace("br", "");
        //}

        public static string SafeString(string strRaw)
        {
            strRaw = strRaw.Replace("'", "''");
            return strRaw;
        }

        public static int Instr(string strTemplate, string strFind)
        {
            if (strTemplate.Length < strFind.Length)
                return -1;
            else
            {
                for (int i = 0; i < strTemplate.Length - strFind.Length + 1; i++)
                    if (strTemplate.Substring(i, strFind.Length) == strFind)
                        return i;
            }
            return -1;

        }

        public static bool ValidateGoodString(string strRaw)
        {
            string[] Bad_String = { "'", "<", ">", "--", "select", "insert", "update", "delete", "drop" };
            for (int i = 0; i < Bad_String.Length; i++)
            {
                if (Instr(strRaw, Bad_String[i]) >= 0)
                    return false;
            }
            return true;
        }

        public static string ConvertArrayToString(string[] strArr)
        {
            string temp = "";
            for (int i = 0; i < strArr.Length; i++)
            {
                temp += strArr[i] + "|";
            }
            return temp.Substring(0, temp.Length - 1);
        }

        public static DateTime convertDateVNtoES(String sDate)
        {
            //try {
            //27/04/1985 -> datetime
            String sDay = sDate.Substring(0, 2);
            String sMonth = sDate.Substring(3, 2);
            String sYear = sDate.Substring(6, 4);
            DateTime time = new DateTime(Int32.Parse(sYear), Int32.Parse(sMonth), Int32.Parse(sDay));
            return time;
            //} catch(Exception aa) {
            //  return null;
            //}
        }

        private static byte[] Unicode2Bytes(String strUnicode)
        {
            Encoding unicode = Encoding.UTF8;
            return unicode.GetBytes(strUnicode);
        }

        private static String Bytes2Unicode(byte[] unicodeBytes)
        {
            Decoder utf8Decoder = Encoding.UTF8.GetDecoder();
            int charCount = utf8Decoder.GetCharCount(unicodeBytes, 0, unicodeBytes.Length);
            Char[] chars = new Char[charCount];
            int charsDecodedCount = utf8Decoder.GetChars(unicodeBytes, 0, unicodeBytes.Length, chars, 0);
            String strUnicode = new String(chars);
            return strUnicode;
        }

        public static string From64StringToUnicode(string s)
        {
            try
            {
                byte[] t = Convert.FromBase64String(s);
                return Bytes2Unicode(t);
            }
            catch (Exception)
            {
                return "";
            }
        }
        
        public static string UnicodeTo64String(string s)
        {
            byte[] t = Unicode2Bytes(s);
            return Convert.ToBase64String(t);
        }

        public static string checkPhoneValid(string phoneNumber)
        {
            string phoneSyntax = "0123456789";

            try
            {
                if (phoneNumber == "") return "";
                string phone = "";
                for (int i = 0; i < phoneNumber.Length; i++)
                    if (phoneSyntax.IndexOf(phoneNumber[i]) != -1)
                        phone += phoneNumber[i];

                if (phone != "" && phone.Length > 8)
                {
                    if (phone.StartsWith("84"))
                    {
                        phone = phone.Substring(2);
                        if (phone.Length != 9 && phone.Length != 10) return "";

                    }
                    else
                        if (phone.StartsWith("0")) phone = phone.Substring(1);
                }
                if (phone.Length != 9 && phone.Length != 10 && phone.Length != 8) return "";

                return phoneViettel(phone);
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        public static string checkPhoneValidAll(string phoneNumber)
        {
            string phoneSyntax = "0123456789";
            try
            {

                if (phoneNumber == "") return "";
                string phone = "";
                for (int i = 0; i < phoneNumber.Length; i++)
                    if (phoneSyntax.IndexOf(phoneNumber[i]) != -1)
                        phone += phoneNumber[i];

                if (phone != "" && phone.Length > 8)
                {
                    if (phone.StartsWith("84"))
                    {
                        phone = phone.Substring(2);
                        if (phone.Length != 9 && phone.Length != 10) return "";

                    }
                    else
                        if (phone.StartsWith("0")) phone = phone.Substring(1);
                }
                if (phone.Length != 9 && phone.Length != 10 && phone.Length != 8) return "";

                return phoneAll(phone);
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        private static string phoneViettel(string phone)
        {
            string wsPhoneViettel = "98,97,168,169,167,166,165";
            string[] tmp = wsPhoneViettel.Split(',');
            for (int i = 0; i < tmp.Length; i++)
                if (phone.StartsWith(tmp[i])) return phone;
            return "";
        }

        private static string phoneAll(string phone)
        {
            string wsPhoneViettel = "98,97,168,169,167,166,165,91,90,93,94,92,95";
            string[] tmp = wsPhoneViettel.Split(',');
            for (int i = 0; i < tmp.Length; i++)
                if (phone.StartsWith(tmp[i])) return phone;
            return "";
        }

        public static string getRandom()
        {
            return rnd.Next(999999999).ToString();
        }

        public static string getRandomSMS()
        {
            return rnd.Next(99999999).ToString();
        }
      

        #endregion

        #region "Connection to DB function"

        public static void FillDataToDropdownListAll(DropDownList ddlList, string TableName, string FieldList)
        {
            string SQL = "SELECT " + FieldList + " FROM " + TableName;
            string[] arrField;
            arrField = FieldList.Split(',');
            DataSet ds = new DataSet();
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnStr);
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                da.Fill(ds, TableName);
                ddlList.DataSource = ds;
                ddlList.DataMember = TableName;
                ddlList.DataValueField = arrField[0];// Field1;
                ddlList.DataTextField = arrField[1];
                ddlList.DataBind();
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }
        
        public static string[] GetDataReaderToStringList(string SQL)
        {
            SQL = SQL.Replace("ExEC", "");
            SQL = SQL.Replace("@", "");
            SQL = SQL.Replace("CAST", "");
            string[] al = null;
            using (SqlConnection conn = new SqlConnection(ConnStr))
            using (SqlCommand cmd = new SqlCommand(SQL, conn))
            {
                try
                {
                    conn.Open();
                    using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection |
                               CommandBehavior.SingleResult))
                    {
                        while (reader.Read())
                        {
                            al = new string[reader.FieldCount];
                            for (int i = 0; i < reader.FieldCount; ++i)
                                al[i] = reader[i].ToString();
                            break;
                        }
                    }
                }
                catch { al = null; }
            }
            return al;
        }
        
        public static int ExecuteQueryNew(string SQL)
        {
            int sResult;
            using (SqlConnection conn = new SqlConnection(ConnStr))
            using (SqlCommand cmd = new SqlCommand(SQL, conn))
            {
                try
                {
                    conn.Open();
                    sResult = cmd.ExecuteNonQuery();
                }
                catch
                {
                    sResult = -1;
                }
            }
            return sResult;
        }
        
        public static void ExecuteQuery(string SQL)
        {
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnStr);
                conn.Open();
                SqlCommand cmd = new SqlCommand(SQL, conn);
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        public static DataSet GetDataSet(string store)
        {
            return GetDataSet(store, ConnStr);
        }
        public static DataSet GetDataSet(string store, SqlCommand cmd)
        {
            return GetDataSet(store, ConnStr, cmd);
        }

        public static DataSet GetDataSet(string store, string connectionString)
        {
            DataSet mDataSet = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = store;
                try
                {
                    conn.Open();
                    //cmd.CommandTimeout = 5;
                    using (SqlDataAdapter reader = new SqlDataAdapter(cmd))
                    {
                        try
                        {
                            mDataSet = new DataSet();
                            reader.Fill(mDataSet);
                        }
                        catch
                        {
                            mDataSet = null;
                        }
                    }
                }
                catch
                {
                    mDataSet = null;
                }
                finally
                {
                    conn.Close();
                }
            }
            return mDataSet;
        }
        public static DataSet GetDataSet(string storeprocedure, string connectionString, SqlCommand cmd)
        {
            DataSet mDataSet = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                cmd.Connection = conn;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = storeprocedure;
                try
                {
                    conn.Open();
                    //cmd.CommandTimeout = 5;
                    using (SqlDataAdapter reader = new SqlDataAdapter(cmd))
                    {
                        try
                        {
                            mDataSet = new DataSet();
                            reader.Fill(mDataSet);
                        }
                        catch
                        {
                            mDataSet = null;
                        }
                    }
                }
                catch (Exception ex)
                {
                    mDataSet = null;
                }
                finally
                {
                    conn.Close();
                }
            }
            return mDataSet;
        }
        

        public static DataView CreateDataView(string SQL)
        {
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnStr);
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt.DefaultView;
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
                return null;
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        public static DataView CreateDataViewLog(string SQL)
        {
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnStrStore);
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt.DefaultView;
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
                return null;
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }


        public static DataView CreateDataViewReport(string SQL)
        {
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnReport);
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt.DefaultView;
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
                return null;
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        public static DataView CreateDataViewReportSMS(string SQL)
        {
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnReportSMS);
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt.DefaultView;
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
                return null;
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        public static DataView CreateDataView(SqlConnection conn, string SQL)
        {

            SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt.DefaultView;
        }
        
        public static DataView CreateDataViewMain(string SQL)
        {

            SqlConnection  conn = new SqlConnection(VatLid.DAL.getConnectionString());
            conn.Open();

            SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt.DefaultView;

            if (conn != null)
                conn.Close();

        }
        
        public static ArrayList GetDataReaderToArrayList(string SQL)
        {
            SqlConnection conn = null;
            SqlDataReader reader = null;
            ArrayList al = new ArrayList();

            try
            {
                conn = new SqlConnection(ConnStr);
                conn.Open();

                SqlCommand cmd = new SqlCommand(SQL, conn);
                reader = cmd.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleResult);
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        string[] fields = new string[reader.FieldCount];
                        for (int i = 0; i < reader.FieldCount; ++i)
                            fields[i] = reader[i].ToString();
                        al.Add(fields);
                    }
                }
            }
            catch (Exception e)
            {
                VatLid.DAL.ExceptionProcess(e);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
                if (reader != null)
                    reader.Close();
            }
            return al;
        }
        public static ArrayList GetDataReaderToArrayList(string connectionString, string SQL)
        {
            SqlConnection conn = null;
            SqlDataReader reader = null;
            ArrayList al = new ArrayList();

            try
            {
                conn = new SqlConnection(connectionString);
                conn.Open();

                SqlCommand cmd = new SqlCommand(SQL, conn);
                reader = cmd.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleResult);
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        string[] fields = new string[reader.FieldCount];
                        for (int i = 0; i < reader.FieldCount; ++i)
                            fields[i] = reader[i].ToString();
                        al.Add(fields);
                    }
                }
            }
            catch (Exception e)
            {
                VatLid.DAL.ExceptionProcess(e);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
                if (reader != null)
                    reader.Close();
            }
            return al;
        }
        
        public static ArrayList GetDataReaderToOneWayArrayList(string SQL)
        {
            SqlConnection conn = null;
            SqlDataReader reader = null;
            ArrayList al = new ArrayList();

            try
            {
                conn = new SqlConnection(ConnStr);
                conn.Open();

                SqlCommand cmd = new SqlCommand(SQL, conn);
                reader = cmd.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleResult);
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        al.Add(reader.GetString(0));
                    }
                }
            }
            catch (Exception e)
            {
                VatLid.DAL.ExceptionProcess(e);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
                if (reader != null)
                    reader.Close();
            }
            return al;
        }
        
        public static void BindDataGrid(System.Web.UI.WebControls.DataGrid dgr, string SQL, string sType)
        {
            string ConnectStr = ConfigurationSettings.AppSettings[sType];
            DataTable table = CreateTableInfo(sType);
            using (SqlConnection conn = new SqlConnection(ConnectStr))
            using (SqlCommand cmd = new SqlCommand(SQL, conn))
            {
                try
                {
                    conn.Open();
                    using (SqlDataAdapter reader = new SqlDataAdapter(cmd))
                    {
                        reader.Fill(table);
                        if (table != null)
                        {
                            dgr.DataSource = table;
                            dgr.DataBind();
                            table.Dispose();
                        }
                    }
                }
                catch (Exception ex)
                {
                    VatLid.DAL.ExceptionProcess(ex);
                }
            }

        }
        
        public static string BindDataGridString(System.Web.UI.WebControls.DataGrid dgr, string SQL, string sType)
        {
            string count = "";
            string ConnectStr = ConfigurationSettings.AppSettings[sType];
            DataTable table = CreateTableInfo(sType);
            using (SqlConnection conn = new SqlConnection(ConnectStr))
            using (SqlCommand cmd = new SqlCommand(SQL, conn))
            {
                try
                {
                    conn.Open();
                    using (SqlDataAdapter reader = new SqlDataAdapter(cmd))
                    {
                        reader.Fill(table);
                        if (table != null)
                        {
                            dgr.DataSource = table;
                            dgr.DataBind();
                            table.Dispose();
                            count = table.Rows.Count + "";
                        }
                    }
                }
                catch (Exception ex)
                {
                    VatLid.DAL.ExceptionProcess(ex);
                }
            }

            return count;

        }
        
        public static DataTable CreateTableInfo(string sType)
        {
            DataTable tb = new DataTable(sType);
            DataColumn ID = new DataColumn("ID", System.Type.GetType("System.Int32"));
            ID.AllowDBNull = true;
            ID.AutoIncrement = true;
            ID.AutoIncrementSeed = 1;
            tb.Columns.Add(ID);
            switch (sType)
            {
                case "viw_Report":
                    DataColumn NameCode = new DataColumn("NameCode", System.Type.GetType("System.String"));
                    tb.Columns.Add(NameCode);
                    DataColumn Service = new DataColumn("Service", System.Type.GetType("System.String"));
                    tb.Columns.Add(Service);
                    DataColumn User_Recv = new DataColumn("User_Recv", System.Type.GetType("System.String"));
                    tb.Columns.Add(User_Recv);
                    DataColumn SMS_Recv = new DataColumn("SMS_Recv", System.Type.GetType("System.String"));
                    tb.Columns.Add(SMS_Recv);
                    DataColumn SMS_Sent = new DataColumn("SMS_Sent", System.Type.GetType("System.String"));
                    tb.Columns.Add(SMS_Sent);
                    DataColumn SMS_Error = new DataColumn("SMS_Error", System.Type.GetType("System.String"));
                    tb.Columns.Add(SMS_Error);
                    DataColumn SMS_Repair = new DataColumn("SMS_Repair", System.Type.GetType("System.String"));
                    tb.Columns.Add(SMS_Repair);
                    DataColumn SMS_Empty = new DataColumn("SMS_Empty", System.Type.GetType("System.String"));
                    tb.Columns.Add(SMS_Empty);
                    DataColumn SMS_Valid = new DataColumn("SMS_Valid", System.Type.GetType("System.String"));
                    tb.Columns.Add(SMS_Valid);
                    DataColumn Money = new DataColumn("Money", System.Type.GetType("System.String"));
                    tb.Columns.Add(Money);
                    DataColumn MoneyVAT = new DataColumn("MoneyVAT", System.Type.GetType("System.String"));
                    tb.Columns.Add(MoneyVAT);
                    DataColumn ARPU = new DataColumn("ARPU", System.Type.GetType("System.String"));
                    tb.Columns.Add(ARPU);
                    break;
                case "MEMBER":
                    DataColumn memberName = new DataColumn("memberName", System.Type.GetType("System.String"));
                    tb.Columns.Add(memberName);
                    DataColumn memberNumber = new DataColumn("memberNumber", System.Type.GetType("System.String"));
                    tb.Columns.Add(memberNumber);
                    DataColumn memberDetails = new DataColumn("memberDetails", System.Type.GetType("System.String"));
                    tb.Columns.Add(memberDetails);
                    break;
                default://"CALLER"
                    DataColumn callerName = new DataColumn("callerName", System.Type.GetType("System.String"));
                    tb.Columns.Add(callerName);
                    DataColumn callerNumber = new DataColumn("callerNumber", System.Type.GetType("System.String"));
                    tb.Columns.Add(callerNumber);
                    DataColumn Description = new DataColumn("description", System.Type.GetType("System.String"));
                    tb.Columns.Add(Description);
                    break;
            }
            DataColumn[] keys = new DataColumn[1];
            keys[0] = ID;
            tb.PrimaryKey = keys;
            return tb;
        }
        
        public static void BindDataGrid(System.Web.UI.WebControls.DataGrid dgr, string SQL)
        {
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnStr);
                conn.Open();
                SqlCommand cmd = new SqlCommand(SQL, conn);
                dgr.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleResult);
                dgr.DataBind();
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);

            }
        }
        
        public static void FetchDataGridColumn(System.Web.UI.WebControls.DataGrid dg, string FieldName)
        {
            BoundColumn bc = new BoundColumn();
            bc.DataField = FieldName;
            dg.Columns.Add(bc);
        }
        
        public static void FetchDataGridColumn(System.Web.UI.WebControls.DataGrid dg, string HeaderText, string FieldName)
        {
            BoundColumn bc = new BoundColumn();
            bc.HeaderText = HeaderText;
            bc.DataField = FieldName;
            dg.Columns.Add(bc);
        }
        
        public static void FetchDataGridColumnPhoneNumber(System.Web.UI.WebControls.DataGrid dg, string HeaderText, string FieldName)
        {
            BoundColumn bc = new BoundColumn();
            bc.HeaderText = HeaderText;
            bc.DataField = FieldName;
            bc.DataFormatString = "{0:####.###.###}";
            dg.Columns.Add(bc);
        }                                          
        
        public static void FetchDataGridColumnDateTime(System.Web.UI.WebControls.DataGrid dg, string HeaderText, string FieldName)
        {
            BoundColumn bc = new BoundColumn();
            bc.HeaderText = HeaderText;
            bc.DataField = FieldName;
            bc.DataFormatString = "{0:dd/MM/yyyy}";
            dg.Columns.Add(bc);
        }
        
        public static void FetchDataGridColumn(System.Web.UI.WebControls.DataGrid dg, string HeaderText, string FieldName, VerticalAlign va, HorizontalAlign ha)
        {
            BoundColumn bc = new BoundColumn();
            bc.HeaderText = HeaderText;
            bc.ItemStyle.VerticalAlign = va;
            bc.ItemStyle.HorizontalAlign = ha;
            bc.DataField = FieldName;
            dg.Columns.Add(bc);
        }
        
        public static void FetchDataGridColumnFormat(System.Web.UI.WebControls.DataGrid dg, string HeaderText, string DataTextField, string DataTextFormatString)
        {
            HyperLinkColumn hlc = new HyperLinkColumn();

            hlc.HeaderText = HeaderText;
            hlc.DataTextField = DataTextField;
            hlc.DataTextFormatString = DataTextFormatString;
            dg.Columns.Add(hlc);

        }
        
        public static void FetchDataGridColumn(System.Web.UI.WebControls.DataGrid dg, string HeaderText, string NavigateField, string NavigateURLString, string Field, int Type)
        {
            if (Type == 1)
            {
                //Add HyperLinkColumn
                HyperLinkColumn hlc = new HyperLinkColumn();
                hlc.HeaderText = HeaderText;
                hlc.DataNavigateUrlField = NavigateField;
                hlc.DataNavigateUrlFormatString = NavigateURLString;
                hlc.DataTextField = Field;
                dg.Columns.Add(hlc);
            }
            else
            {
                //Add HyperLinkColumn
                HyperLinkColumn hlc = new HyperLinkColumn();
                hlc.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                hlc.HeaderText = HeaderText;
                hlc.DataNavigateUrlField = NavigateField;
                hlc.DataNavigateUrlFormatString = NavigateURLString;
                hlc.Text = Field;
                hlc.ItemStyle.VerticalAlign = VerticalAlign.Middle;
                hlc.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                dg.Columns.Add(hlc);
            }
        }
       
        public static void FetchDataGridColumn1(System.Web.UI.WebControls.DataGrid dg, string HeaderText, string NavigateField, string NavigateURLString, string Field, int Type)
        {
            if (Type == 1)
            {
                //Add HyperLinkColumn
                HyperLinkColumn hlc = new HyperLinkColumn();
                hlc.HeaderText = HeaderText;
                hlc.DataNavigateUrlField = NavigateField;
                hlc.DataNavigateUrlFormatString = NavigateURLString;
                hlc.DataTextField = Field;
                dg.Columns.Add(hlc);
            }
            else
            {
                //Add HyperLinkColumn
                HyperLinkColumn hlc = new HyperLinkColumn();
                hlc.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                hlc.HeaderText = HeaderText;
                hlc.DataNavigateUrlField = NavigateField;
                hlc.DataNavigateUrlFormatString = NavigateURLString;
                hlc.Text = Field;
                hlc.ItemStyle.VerticalAlign = VerticalAlign.Middle;
                hlc.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                hlc.Target = "_blank";               
                dg.Columns.Add(hlc);
            }
        }
        
        public static void FillDataToDropdownList(DropDownList ddlList, string SQL, string TableName, string FieldList)
        {
            //string SQL = "SELECT " + FieldList + " FROM " + TableName;
            string[] arrField;
            arrField = FieldList.Split(',');
            DataSet ds = new DataSet();
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnStr);
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                da.Fill(ds, TableName);
                ddlList.DataSource = ds;
                ddlList.DataMember = TableName;
                ddlList.DataValueField = arrField[0];// Field1;
                ddlList.DataTextField = arrField[1];// Field2;			
                ddlList.DataBind();
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }
        
        public static void FillDataToDropdownList(DropDownList ddlList, string TableName, string FieldList)
        {
            string SQL = "SELECT " + FieldList + " FROM " + TableName;
            string[] arrField;
            arrField = FieldList.Split(',');
            DataSet ds = new DataSet();
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnStr);
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                da.Fill(ds, TableName);
                ddlList.DataSource = ds;
                ddlList.DataMember = TableName;
                ddlList.DataValueField = arrField[0];// Field1;
                ddlList.DataTextField = arrField[1];// Field2;			
                ddlList.DataBind();
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        public static void FillDataToDropdownListReport(DropDownList ddlList, string TableName, string FieldList)
        {
            string SQL = "SELECT " + FieldList + " FROM " + TableName;
            string[] arrField;
            arrField = FieldList.Split(',');
            DataSet ds = new DataSet();
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnReport);
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                da.Fill(ds, TableName);
                ddlList.DataSource = ds;
                ddlList.DataMember = TableName;
                ddlList.DataValueField = arrField[0];// Field1;
                ddlList.DataTextField = arrField[1];// Field2;			
                ddlList.DataBind();
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        public static void FillDataToDropdownListDUTD(DropDownList ddlList, string TableName, string FieldList)
        {
            string SQL = "SELECT " + FieldList + " FROM " + TableName;
            string[] arrField;
            arrField = FieldList.Split(',');
            DataSet ds = new DataSet();
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnDUTD);
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                da.Fill(ds, TableName);
                ddlList.DataSource = ds;
                ddlList.DataMember = TableName;
                ddlList.DataValueField = arrField[0];// Field1;
                ddlList.DataTextField = arrField[1];// Field2;			
                ddlList.DataBind();
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        
        public static void FillDataToDropdownListReport(DropDownList ddlList, string TableName, string SQL, string FieldList, string sType)
        {
            string ConnectStr = ConfigurationSettings.AppSettings[sType];
            string[] arrField;
            arrField = FieldList.Split(',');
            DataSet ds = new DataSet();
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnectStr);
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                da.Fill(ds, TableName);
                ddlList.DataSource = ds;
                ddlList.DataMember = TableName;
                ddlList.DataValueField = arrField[0];// Field1;
                ddlList.DataTextField = arrField[1];// Field2;			
                ddlList.DataBind();
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        public static void ChangeDataGridColumn(System.Web.UI.WebControls.DataGrid dgr, int iColumn, string sOldContent, string sNewContent)
        {
            int i;
            for (i = 0; i < dgr.Items.Count; i++)
            {

               // VatLid.MessageBox.Show(dgr.Items[i].Cells[iColumn].Text);
                dgr.Items[i].Cells[iColumn].Text = dgr.Items[i].Cells[iColumn].Text.Replace(sOldContent, sNewContent);

            }
        }

        public static string[] GetDataReaderToStringList(string SQL, string connectionString)
        {
            string[] al = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            using (SqlCommand cmd = new SqlCommand(SQL, conn))
            {
                try
                {
                    conn.Open();
                    using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection |
                               CommandBehavior.SingleResult))
                    {
                        while (reader.Read())
                        {
                            al = new string[reader.FieldCount];
                            for (int i = 0; i < reader.FieldCount; ++i)
                                al[i] = reader[i].ToString();
                            break;
                        }
                    }
                }
                catch { al = null; }
            }
            return al;
        }

        public static void FillDataToCheckBoxList(CheckBoxList checkList, string TableName, string FieldList)
        {
            string SQL = "SELECT " + FieldList + " FROM " + TableName;
            string[] arrField;
            arrField = FieldList.Split(',');
            DataSet ds = new DataSet();
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnStr);
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                da.Fill(ds, TableName);
                checkList.DataSource = ds;
                checkList.DataMember = TableName;
                checkList.DataValueField = arrField[0];// Field1;
                checkList.DataTextField = arrField[1];// Field2;			
                checkList.DataBind();
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        public static String getParameters(String Field, String TableName, String dieukien)
        {
            string SQL = "SELECT " + Field + " FROM " + TableName + " " + dieukien;
            DataSet ds = new DataSet();
            SqlConnection conn = null;
            String mailto = "";
            try
            {
                conn = new SqlConnection(ConnStr);
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                da.Fill(ds, TableName);
                DataRowCollection rows = ds.Tables[TableName].Rows;
                for (int tt = 0; tt < rows.Count; tt++)
                {
                    mailto += (String)rows[tt][Field].ToString() + ",";
                }
                mailto = mailto.TrimEnd(new char[] { ',' });
            }
            catch (Exception e)
            {
                //return e.ToString();
                VatLid.DAL.ExceptionProcess(e);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
            return mailto;
        }

        #endregion        
                               
        #region "Permission"

        public static void ReGenerateRightsFromUserGroupsAndSysFuncs()
        {
            try
            {
                string SQL;
                SQL = "DELETE FROM Rights";
                VatLid.DAL.ExecuteQuery(SQL);
                ArrayList alUserGroups = GetDataReaderToArrayList("Select ID from UserGroups");
                string[][] arrUserGroups = (string[][])alUserGroups.ToArray(typeof(string[]));
                int iUserGroupsCount = alUserGroups.Count;
                ArrayList alSysFuncs = GetDataReaderToArrayList("Select ID from SysFuncs");
                string[][] arrSysFuncs = (string[][])alSysFuncs.ToArray(typeof(string[]));
                int iSysFuncsCount = alSysFuncs.Count;
                for (int i = 0; i < iUserGroupsCount; i++)
                {
                    for (int j = 0; j < iSysFuncsCount; j++)
                    {
                        SQL = "INSERT INTO Rights(UserGroupID,FuncID,RightsType) VALUES(" + arrUserGroups[i][0] + "," + arrSysFuncs[j][0] + ",'" + "group" + "'" + ")";
                        ExecuteQuery(SQL);
                    }

                }
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
            }

        }

        public static bool GetRights(string groupid, string FuncFile)
        {

            //return true;

           // int leng = FuncFile.IndexOf("/") + 1;

           // string path = FuncFile.Substring(leng);

            string path = FuncFile;

            try
            {

                SqlParameter[] parameters = { 
                new SqlParameter("@USERGROUPID", SqlDbType.Int),	
                new SqlParameter("@ItemParent", SqlDbType.NVarChar),                			        	                        
                };

                parameters[0].Value = Convert.ToInt32(groupid);
                parameters[1].Value = path;

                DataSet ds = null;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "system_item$SelectcheckRight", parameters);

                DataTable dt = new DataTable();
                dt = ds.Tables[0];

                if (dt.Rows.Count > 0)
                    return true;
                else
                    return false;

            }
            catch (Exception e)
            {
                ExceptionProcess(e);
                return false;
            }
        }

        public static string GetSystemID( string FuncFile)
        {
            int leng = FuncFile.IndexOf("/") + 1;

            string path = FuncFile.Substring(leng);
          
          
            try
            {

                SqlParameter[] parameters = { 
             
                new SqlParameter("@ItemParent", SqlDbType.NVarChar),
                			        	                        
                };

             
                parameters[0].Value = path;

                DataSet ds = null;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "system_item$GetItemID", parameters);

                DataTable dt = new DataTable();
                dt = ds.Tables[0];

                if (dt.Rows.Count > 0)
                    return dt.Rows[0]["ItemName"].ToString();
                else
                    return "";

            }
            catch (Exception e)
            {
                ExceptionProcess(e);
                return "";
            }
        }   
        
        
        public static bool isViewed(string sUserName, string sFileName)
        {
            return true;
        }      

        
        public static int getType(string groupid, string sFileName)
        {
            int result = 1;

            try
            {             
                    int leng = sFileName.IndexOf("/") + 1;

                    string path = sFileName;// sFileName.Substring(leng);


                    SqlParameter[] parameters = { 
                    new SqlParameter("@groupid", SqlDbType.NVarChar),	
			        new SqlParameter("@FileName", SqlDbType.NVarChar),	    	        
                    
                    };
                    parameters[0].Value = groupid;
                    parameters[1].Value = path;

                    DataSet ds = null;
                    ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "system_item$SelectUserAuthen", parameters);

                    DataTable dt = new DataTable();
                    dt = ds.Tables[0];


                    if (dt.Rows.Count > 0)
                        result = Convert.ToInt32(dt.Rows[0]["type"].ToString());
                    else
                        result = 1;

                    return result;
               
            }
            catch (Exception e)
            {
                ExceptionProcess(e);
                return 1;
            }
        }


        #endregion

        #region "Format Content"

        public static string FormatSave(string Html)
        {
            Html = Html.Replace("http://115.84.178.52/", "./");
            Html = Html.Replace(VatLid.Variables.sLinkToResource, "./");
            Html = Html.Replace("/cms/", "./");
            Html = Html.Replace("/CMS/", "./");
            Html = Html.Replace("../../../archive/images", "./archive/images");
            Html = Html.Replace("../../archive/images", "./archive/images");
            Html = Html.Replace("../archive/images", "./archive/images");

            Html = Html.Replace("http://images.dailyinfo.vn/archive/images", "/archive/images");

            Html = Html.Replace("http://img1.dailyinfo.vn/archive/images", "/archive/images");
            Html = Html.Replace("http://img2.dailyinfo.vn/archive/images", "/archive/images");
            Html = Html.Replace("http://img3.dailyinfo.vn/archive/images", "/archive/images");

            Html = Html.Replace("http://images.dailyinfo.vn/archive/flashs", "/archive/flashs");
            Html = Html.Replace("http://images.dailyinfo.vn/archive/files", "/archive/files");

            Html = Html.Replace("/archive/images", "./archive/images");
            Html = Html.Replace("/archive/flashs", "http://images.dailyinfo.vn/archive/flashs");
            Html = Html.Replace("/archive/files", "http://images.dailyinfo.vn/archive/files");
            Html = Html.Replace("./archive/media", "http://images.dailyinfo.vn/archive/media");
            Html = Html.Replace(".http://", "http://");
            Html = Html.Replace(".../http://", "http://");

            return Html;
        }
        
            
        public static string FormatView(string Html)
        {
            string s = VatLid.Variables.sLinkToResource + "image/";

            Html = Html.Replace("../../image/", s);
            Html = Html.Replace("../image/", s);
            Html = Html.Replace("./image/", s);
            Html = Html.Replace("../../Image/", s);
            Html = Html.Replace("../Image/", s);
            Html = Html.Replace("./Image/", s);

            Html = Html.Replace("/cms/", "/");
            Html = Html.Replace("../../../archive/images", "/archive/images");
            Html = Html.Replace("../../archive/images", "/archive/images");
            Html = Html.Replace("../archive/images", "/archive/images");
            Html = Html.Replace("./archive/images", "/archive/images");
            Html = Html.Replace(".../http://", "http://");
            Html = Html.Replace("http://115.84.178.52/", VatLid.Variables.sLinkToResource); //swich to new ip

            return Html;
        }

        #endregion

        #region "Common"
        
        public static string GenNiceUrl(Object objurl)
        {
            try
            {
                String url = objurl.ToString();
                String niceurl = ConvertVietnameseCharacterToEN(url);

                niceurl = StripTags(niceurl);
                niceurl = niceurl.Replace(" ", "-");
                niceurl = niceurl.Replace("_", "-");
                niceurl = niceurl.Replace("nbsp;", "-");


                niceurl = removeChar(niceurl, new String[] { "'", "/", "m²", ":", ",", "<", ">", "”", "“", ".", "!", "?", "@", "#", "$", "%", "^", "&", "*", "(", ")", "+", "~", "`", "\"" });

                niceurl = niceurl.ToLower();

                //Fix loi 'hu.html' o cuoi trang
                niceurl = niceurl.Replace("uy", "di");

                return niceurl;
            }
            catch
            {
                return "page";
            }
        }

       

        public static String removeChar(String niceurl, String[] danhsach)
        {
            foreach (String xoa in danhsach)
            {
                niceurl = niceurl.Replace(xoa, "");
            }
            return niceurl;
        }
        
        #endregion

        #region "Sync"

        /// <summary>
        /// Get all link image in page
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static List<String> GetAllImagesInPage(string html)
        {
            Regex Tags = new Regex("<.*?>", RegexOptions.Compiled | RegexOptions.Singleline);
            MatchCollection matchCollection = Tags.Matches(html);

            List<String> links_image = new List<string>();

            foreach (Match match in matchCollection)
            {
                string true_tag = match.Value;
                string tag = true_tag.ToLower();

                if (tag.Contains("<img"))
                {
                    string src = Regex.Match(tag, @"(src)\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?").Value;

                    if (src.Trim().Length > 0) //?nh
                    {
                        src = src.Replace("src", "");
                        src = src.Replace("'", "");
                        src = src.Replace("\"", "");
                        src = src.Replace("=", "");

                        if (!src.Contains("http")) // Khong co http
                        {
                            src = src.Replace("/cmsdiv2", "");                            
                            src = src.Replace("./image/", "http://images.dailyinfo.vn/image/");
                            src = src.Replace("../archive/images", "http://images.dailyinfo.vn/archive/images");
                            src = src.Replace("./archive/images", "http://images.dailyinfo.vn/archive/images");
                            src = src.Replace("/CMS/archive/images", "http://images.dailyinfo.vn/archive/images");
                                                      

                        }

                        links_image.Add(src);
                    }
                }
            }

            return links_image;
        }
        
        public static void SyncImagesInsert(string link)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
				    new SqlParameter("@link", SqlDbType.NVarChar),				
				};
                parameters[0].Value = link;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.getConnectionStringSync(), CommandType.StoredProcedure, "SyncImages$Insert", parameters);
            }

            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void GetAllMediaInMessages(string id)
        {
            try
            {
                List<String> list_images = new List<String>();

                SqlParameter[] parameters = 
			    { 
				    new SqlParameter("@id", SqlDbType.Int),				
				};
                parameters[0].Value = id;

                DataSet ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "cms_Messages$GetAllMedia", parameters);

                DataTable dt_link = ds.Tables[0];
                for (int i = 0; i < dt_link.Rows.Count; i++)
                {
                    string src = dt_link.Rows[i]["src"].ToString();
                    list_images.Add(@VatLid.Variables.sImageSync + src);
                }

                //Get image in page
                DataTable dt_content = ds.Tables[1];

                string content = dt_content.Rows[0]["Content"].ToString();
                string link_image = dt_content.Rows[0]["LeadImage"].ToString();

                content = VatLid.DAL.FormatSave(content);
                list_images.Add(@VatLid.Variables.sImageSync + link_image);

                List<String> list_image_inpage = VatLid.DAL.GetAllImagesInPage(content);
                if (list_image_inpage.Count > 0)
                {
                    foreach (String item in list_image_inpage)
                    {
                        list_images.Add(item);
                    }
                }

                //Sync
                if (list_images.Count > 0)
                {
                    foreach (String item in list_images)
                    {
                        if (item.Contains("http://images.dailyinfo.vn"))
                            VatLid.DAL.SyncImagesInsert(item);
                    }
                }
            }
            catch { };
        }

        #endregion

        public static void INSERT_USER_USE(string UserID, string ITEMCODE, string ITEMNAME)
        {
            try
            {
                SqlParameter[] parameters = 
									    { 
										    new SqlParameter("@UserID", SqlDbType.NVarChar ),
										    new SqlParameter("@ITEMCODE", SqlDbType.NVarChar),
										    new SqlParameter("@ITEMNAME", SqlDbType.NVarChar ),
                                            
    										
					    };
                parameters[0].Value = UserID;
                parameters[1].Value = ITEMCODE;
                parameters[2].Value = ITEMNAME;


                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "Insert_User_Download", parameters);
            }

            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void INSERT_USER_LOG(string UserID, string ActionName, string ActionDesc, string ActionStatus, string ip)
        {
            try
            {
                SqlParameter[] parameters = 
                                        { 
                                            new SqlParameter("@UserID", SqlDbType.NVarChar ),
                                            new SqlParameter("@ActionName", SqlDbType.NVarChar),
                                            new SqlParameter("@ActionDesc", SqlDbType.NVarChar ),
                                            new SqlParameter("@ActionStatus", SqlDbType.NVarChar ),
                                            new SqlParameter("@ip", SqlDbType.NVarChar ),
                                            
    										
                        };
                parameters[0].Value = UserID;
                parameters[1].Value = ActionName;
                parameters[2].Value = ActionDesc;
                parameters[3].Value = ActionStatus;
                parameters[4].Value = ip;


                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "cms_ACTION_LOG$INSERT", parameters);
            }

            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void INSERT_SYSTEM_LOG(int UserID, string Type, string ItemID, string Status, string logid)
        {
            try
            {
                SqlParameter[] parameters = 
									    { 
										    new SqlParameter("@UserID", SqlDbType.Int ),
										    new SqlParameter("@Type", SqlDbType.NVarChar),
										    new SqlParameter("@ItemID", SqlDbType.NVarChar ),
                                            new SqlParameter("@Status", SqlDbType.NVarChar ),
                                            new SqlParameter("@logids", SqlDbType.NVarChar ),
                                            
    										
					    };
                parameters[0].Value = UserID;
                parameters[1].Value = Type;
                parameters[2].Value = ItemID;
                parameters[3].Value = Status;
                parameters[4].Value = logid;


                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.getConnStrStore(), CommandType.StoredProcedure, "System_Log$InsertBatch", parameters);
            }

            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        } 

        
        #region "DAL"

        public static void UpdateStatus(string sTableName, string sFieldName, int intvalue, string ID, string sID)
        {
            string SQL = "";
            try
            {
                SQL = "UPDATE " + sTableName + " SET " + sFieldName + " = " + intvalue + " WHERE " + ID + " in (" + sID + ")";
                VatLid.DAL.ExecuteQuery(SQL);
            }
            catch (Exception e)
            {
                VatLid.DAL.ExceptionProcess(e);
            }
        }

        public static void UpdateStatus(string sTableName, string sFieldName, int intvalue, string sID)
        {
            string SQL = "";
            try
            {
                SQL = "UPDATE " + sTableName + " SET " + sFieldName + " = " + intvalue + " WHERE ID in (" + sID + ")";
                VatLid.DAL.ExecuteQuery(SQL);
            }
            catch (Exception e)
            {
                VatLid.DAL.ExceptionProcess(e);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="mids"></param>
        /// <param name="type"></param>
        public static void UserLogs_InsertBatch(int uid, string mids, int type)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
				    new SqlParameter("@uid", SqlDbType.Int ),
				    new SqlParameter("@mids", SqlDbType.NVarChar),
				    new SqlParameter("@type", SqlDbType.Int )
				};
                parameters[0].Value = uid;
                parameters[1].Value = mids;
                parameters[2].Value = type;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.getConnStrStore(), CommandType.StoredProcedure, "cms_UserLogs$InsertBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void UserLogs_InsertBatchPerson(int uid, string mids, int type)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
				    new SqlParameter("@uid", SqlDbType.Int ),
				    new SqlParameter("@mids", SqlDbType.NVarChar),
				    new SqlParameter("@type", SqlDbType.Int )
				};
                parameters[0].Value = uid;
                parameters[1].Value = mids;
                parameters[2].Value = type;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.getConnStrStore(), CommandType.StoredProcedure, "cms_UserLogsPerson$InsertBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void UserLogs_InsertBatchEvent(int uid, string mids, int type)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
				    new SqlParameter("@uid", SqlDbType.Int ),
				    new SqlParameter("@mids", SqlDbType.NVarChar),
				    new SqlParameter("@type", SqlDbType.Int )
				};
                parameters[0].Value = uid;
                parameters[1].Value = mids;
                parameters[2].Value = type;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.getConnStrStore(), CommandType.StoredProcedure, "cms_UserLogsEvent$InsertBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }       

        public static void Messages_SetStatusBatch(string mids, int type)
        {
            try
            {
                SqlParameter[] parameters = 
                { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
                    new SqlParameter("@type", SqlDbType.Int),
                };
                parameters[0].Value = mids;
                parameters[1].Value = type;

             

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_Messages$SetStatusBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }



        public static void Messages_SetCacheSuperBatch(string mids, int type, int mess_type)
        {
            try
            {
                SqlParameter[] parameters = 
                { 
                    new SqlParameter("@ids", SqlDbType.NVarChar),
                    new SqlParameter("@type", SqlDbType.Int),
                    new SqlParameter("@mess_type", SqlDbType.Int),
                };
                parameters[0].Value = mids;
                parameters[1].Value = type;
                parameters[2].Value = mess_type;



                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_Cache_Super$SetBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }



        public static Boolean Messages_CheckSetStatus(string mids, int type)
        {
            Boolean result = false;
            try
            {
                SqlParameter[] parameters = 
                { 
                    new SqlParameter("@id", SqlDbType.NVarChar),
                    new SqlParameter("@type", SqlDbType.Int),
                };
                parameters[0].Value = mids;
                parameters[1].Value = type;
                
                DataSet ds;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "cms_Messages$SelectStatus", parameters);

                if (ds.Tables[0].Rows.Count > 0)
                {
                    result = true;
                }
                else
                {
                    result = false;
                }


            }
            catch (Exception ex)
            {
                result = false;
            }

            return result;
        }

        public static void StatusSet_SetStatusBatch(string mids, int type, int typeMess)
        {
            try
            {
                SqlParameter[] parameters = 
                { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
                    new SqlParameter("@type", SqlDbType.Int),
                    new SqlParameter("@typeMess", SqlDbType.Int),
                };
                parameters[0].Value = mids;
                parameters[1].Value = type;
                parameters[2].Value = typeMess;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_StatusSet$SetStatusBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void StatusSetOrther_SetStatusBatch(string mids, int type)
        {
            try
            {
                SqlParameter[] parameters = 
                { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
                    new SqlParameter("@type", SqlDbType.Int),
                    
                };
                parameters[0].Value = mids;
                parameters[1].Value = type;
                

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_StatusSetother$SetStatusBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void Messages_DeletePublishBatch(string mids, int status)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				    new SqlParameter("@status", SqlDbType.Int),
				};
                parameters[0].Value = mids;
                parameters[1].Value = status;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_Messages$DeletePublishBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void MessagesEvent_DeletePublishBatch(string mids, int status)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				    new SqlParameter("@status", SqlDbType.Int),
				};
                parameters[0].Value = mids;
                parameters[1].Value = status;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesEvent$DeletePublishBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void MessagesPerson_DeletePublishBatch(string mids, int status)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				    new SqlParameter("@status", SqlDbType.Int),
				};
                parameters[0].Value = mids;
                parameters[1].Value = status;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesPerson$DeletePublishBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void MessagesEvent_AwaitPublishBatch(string mids, int status)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				    new SqlParameter("@status", SqlDbType.Int),
				};
                parameters[0].Value = mids;
                parameters[1].Value = status;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesEvent$StatusSetBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void MessagesPerson_AwaitPublishBatch(string mids, int status)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				    new SqlParameter("@status", SqlDbType.Int),
				};
                parameters[0].Value = mids;
                parameters[1].Value = status;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesPerson$StatusSetBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void Messages_AwaitPublishBatch(string mids, int status)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				    new SqlParameter("@status", SqlDbType.Int),
				};
                parameters[0].Value = mids;
                parameters[1].Value = status;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_Messages$statusSetBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void Messages_DateInsertBatch(string mids, int status)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				    new SqlParameter("@status", SqlDbType.Int),
				};
                parameters[0].Value = mids;
                parameters[1].Value = status;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_Mess_Date$SetDateBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void Messages_SetStatusBatchPublish(string mids)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				   
				};
                parameters[0].Value = mids;


                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_Messages$SetStatusBatchPublish", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }


        public static void Messages_deleteStatusWaitidBatch(string mids)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				   
				};
                parameters[0].Value = mids;


                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_Messages$deleteStatusWaitidBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

       

        public static void MessagesEvent_SetStatusBatchPublish(string mids)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				   
				};
                parameters[0].Value = mids;


                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesEvent$SetStatusBatchPublish", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void MessagesEvent_SetStatusBatchPublish(string mids, int type)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
                    new SqlParameter("@type", SqlDbType.Int),
				   
				};
                parameters[0].Value = mids;
                parameters[1].Value = type;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesEvent$SetStatusBatchPublish", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void MessagesPerson_SetStatusBatchPublish(string mids)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				   
				};
                parameters[0].Value = mids;


                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesPerson$SetStatusBatchPublish", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }


        public static void StatusWait_SetStatusBatch(string mids, int type)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				    new SqlParameter("@type", SqlDbType.Int),
				};
                parameters[0].Value = mids;
                parameters[1].Value = type;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_StatusWait$SetStatusBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }


        public static void MessagesEvent_SetStatusBatch(string mids, int type, int status)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				    new SqlParameter("@type", SqlDbType.Int),
                    new SqlParameter("@Status", SqlDbType.Int),
				};
                parameters[0].Value = mids;
                parameters[1].Value = type;
                parameters[2].Value = status;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesEvent$SetStatusBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void MessagesEvent_SetTopBatch(string mids, int type)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				    new SqlParameter("@type", SqlDbType.Int),
                    
				};
                parameters[0].Value = mids;
                parameters[1].Value = type;
                

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesEvent$SetTopBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }


        public static void MessagesPerson_SetStatusBatch(string mids, int type, int status)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				    new SqlParameter("@type", SqlDbType.Int),
                    new SqlParameter("@Status", SqlDbType.Int),
				};
                parameters[0].Value = mids;
                parameters[1].Value = type;
                parameters[2].Value = status;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesPerson$SetStatusBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void MessagesPerson_SetTopBatch(string mids, int type, int status)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				    new SqlParameter("@type", SqlDbType.Int),
                    new SqlParameter("@Status", SqlDbType.Int),
				};
                parameters[0].Value = mids;
                parameters[1].Value = type;
                parameters[2].Value = status;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesPerson$SetTopBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }


        public static void SentenceInDay_SetShow(string id)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@id", SqlDbType.Int),				   
				};
                parameters[0].Value = Convert.ToInt32(id);

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_SentenceInDay$SetShow", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }


        public static void Messages_SetStatus(int mid, int other_id, int type)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mid", SqlDbType.Int),
                    new SqlParameter("@other_id", SqlDbType.Int),
				    new SqlParameter("@type", SqlDbType.Int),
				};
                parameters[0].Value = mid;
                parameters[1].Value = other_id;
                parameters[2].Value = type;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_Messages$SetStatus", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static int BoxGetPositionPersistent(string PositionID)
        {
            int value= 0;
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@PositionID", SqlDbType.NVarChar),
				};
                parameters[0].Value = Convert.ToInt32(PositionID);

                DataSet ds;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "cms_Position$getPersistent", parameters);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    value = 1;
                }

                return value;

            }
            catch (Exception ex)
            {
                return value;
            }
        }



        //public static int BoxGetPositionPersistent(string PositionID)
        //{
        //    try
        //    {
        //        string SQL = "SELECT Persistent FROM Position WHERE Persistent=1 AND ID=" + PositionID;
        //        ArrayList al = GetDataReaderToArrayList(SQL);

        //        if (al.Count != 0)
        //            return 1;
        //        else
        //            return 0;
        //    }
        //    catch (Exception e)
        //    {
        //        ExceptionProcess(e);
        //        return 0;
        //    }
        //}

        public static void Messages_PublishBatch(string mids, int uid)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
                    new SqlParameter("@uid", SqlDbType.Int),
				};
                parameters[0].Value = mids;
                parameters[1].Value = uid;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_Messages$PublishBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void Messages_SyncImages(string id)
        {
            try
            {
                
                List<String> list_images = new List<String>();                

                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@id", SqlDbType.NVarChar),                    
				};
                parameters[0].Value = id;
                DataSet ds;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "cms_Messages$GetAllMedia", parameters);

                if (ds.Tables[1].Rows.Count > 0)
                {
                    List<String> list_image_inpage = VatLid.DAL.GetAllImagesInPage(ds.Tables[1].Rows[0]["Content"].ToString());

                    //Get image in page
                    if (list_image_inpage.Count > 0)
                    {
                        foreach (String item in list_image_inpage)
                        {
                            list_images.Add(item);
                        }
                    }


                    list_images.Add("http://images.dailyinfo.vn/" + ds.Tables[1].Rows[0]["LeadImage"].ToString());
                }

                if (ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        list_images.Add("http://images.dailyinfo.vn/" + ds.Tables[0].Rows[i]["src"].ToString());
                    }
                }

                //Sync
                if (list_images.Count > 0)
                {
                    foreach (String item in list_images)
                    {
                        VatLid.DAL.SyncImagesInsert(item);
                    }
                }
               

            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static bool DownloadFile(string _URL, string _SaveAs)
        {
            Boolean result = false;

            try
            {
                string imdDBLocal = VatLid.Variables.sPathToResourceKTTD + _SaveAs.Replace("http://images.dailyinfo.vn", "");

                string path = imdDBLocal.Substring(0, imdDBLocal.LastIndexOf("/") + 1);

                if (!System.IO.Directory.Exists(path))
                    Directory.CreateDirectory(path);

                string filepath = imdDBLocal;
                if (File.Exists(filepath))
                {
                    File.Delete(filepath);
                }


                System.Net.WebClient _WebClient = new System.Net.WebClient();

                _WebClient.DownloadFile(_URL, filepath);
                result = true;
            }
            catch (Exception _Exception)
            {
                result = false;
            }
            return result;
        }


        public static void Messages_CopyImagesDUTD(string id)
        {
            try
            {

                List<String> list_images = new List<String>();

                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@id", SqlDbType.NVarChar),                    
				};
                parameters[0].Value = id;
                DataSet ds;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "cms_Messages$GetAllMedia", parameters);

                if (ds.Tables[1].Rows.Count > 0)
                {
                   List<String> list_image_inpage = VatLid.DAL.GetAllImagesInPage(ds.Tables[1].Rows[0]["Content"].ToString());

                   //Get image in page
                   if (list_image_inpage.Count > 0)
                   {
                       foreach (String item in list_image_inpage)
                       {
                           string pathA = item.ToString().Replace("./Image", "Image");
                           ///pathA = pathA.Replace("http://images.dailyinfo.vn", "\archive");

                           DownloadFile(item.ToString().Replace("./Image", "Image"), pathA);
                           //list_images.Add(item);
                       }
                   }


                    list_images.Add(ds.Tables[1].Rows[0]["LeadImage"].ToString());
                }

                if (ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        list_images.Add( ds.Tables[0].Rows[i]["src"].ToString());
                    }
                }
          
            
                ////Sync
                if (list_images.Count > 0)
                {
                    foreach (String item in list_images)
                    {
                        string path = item.ToString().Replace("./Image", "Image");
                      

                        if (FileToByteArray(VatLid.Variables.sPathToResource + path.Replace("http://images.dailyinfo.vn", "").Replace("/", "\\")) == null)
                        {
                            path = path.Replace("http://images.dailyinfo.vn", "");
                            path = path.Replace("/", "\\");
                            addImageToFile(item.ToString(), FileToByteArray(VatLid.Variables.sPathToResourceImage + path));
                        }
                        else
                        {
                            path = path.Replace("http://images.dailyinfo.vn", "\archive");
                            path = path.Replace("/", "\\");
                            addImageToFile(item.ToString(), FileToByteArray(VatLid.Variables.sPathToResource + path));
                        }
                      
                    }
                }


            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

       

        public static byte[] FileToByteArray(string _FileName)
	    {
	        byte[] _Buffer = null;
    	 
	        try
	        {
	            // Open file for reading
	            System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
    	         
            // attach filestream to binary reader
	            System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
             
	            // get total byte length of the file
	            long _TotalBytes = new System.IO.FileInfo(_FileName).Length;
    	         
	            // read entire file into buffer
	            _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes);
    	         
	            // close file reader
	            _FileStream.Close();
	            _FileStream.Dispose();
	            _BinaryReader.Close();
	        }
	        catch (Exception _Exception)
	        {
                _Buffer = null;
	            // Error
	            Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
	        }
    	 
	        return _Buffer;
	    }


        public static void addImageToFile(string id, byte[] imgdata)
        {
            try
            {
                string imdDBLocal = VatLid.Variables.sPathToResourceKTTD + id.Replace("http://images.dailyinfo.vn", "");

                string path = imdDBLocal.Substring(0, imdDBLocal.LastIndexOf("/") + 1);

                if (!System.IO.Directory.Exists(path))
                    Directory.CreateDirectory(path);

                string filepath = imdDBLocal;
                if (File.Exists(filepath))
                {
                    File.Delete(filepath);
                }
                FileStream fStream = new FileStream(filepath, FileMode.CreateNew);
                BinaryWriter bw = new BinaryWriter(fStream);
                bw.Write(imgdata);
                bw.Close();
                fStream.Close();
            }
            catch (Exception ex)
            {
               
            }
        }


        public static void MessagesEvent_PublishBatch(string mids, int uid)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
                    new SqlParameter("@uid", SqlDbType.Int),
				};
                parameters[0].Value = mids;
                parameters[1].Value = uid;


                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesEvent$PublishBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void MessagesPerson_PublishBatch(string mids, int uid)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
                    new SqlParameter("@uid", SqlDbType.Int),
				};
                parameters[0].Value = mids;
                parameters[1].Value = uid;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesPerson$PublishBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void Messages_UnPublishBatch(string mids)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				};
                parameters[0].Value = mids;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_Messages$UnPublishBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void Messages_StatusSetBatch(string mids, int status)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
                    new SqlParameter("@status", SqlDbType.Int),
				};
                parameters[0].Value = mids;
                parameters[1].Value = status;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_Messages$statusSetBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }


        public static void MessagesEvent_UnPublishBatch(string mids)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				};
                parameters[0].Value = mids;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesEvent$UnPublishBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void MessagesPerson_UnPublishBatch(string mids)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				};
                parameters[0].Value = mids;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesPerson$UnPublishBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }


        public static void Messages_DeleteBatch(string mids)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				};
                parameters[0].Value = mids;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_Messages$DeleteBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void MessagesEvent_DeleteBatch(string mids)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				};
                parameters[0].Value = mids;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesEvent$DeleteBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static void MessagesPerson_DeleteBatch(string mids)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@mids", SqlDbType.NVarChar),
				};
                parameters[0].Value = mids;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_MessagesPerson$DeleteBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }


        public static string getTitle(string mid)
        {
            string title = "";
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@id", SqlDbType.NVarChar),
				};
                parameters[0].Value = mid;

                DataSet ds;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "cms_Messages$getTitleByID", parameters);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    title = ds.Tables[0].Rows[0]["title"].ToString();                   
                }

                return title;
               
            }
            catch (Exception ex)
            {
                return title;
            }
        }

        public static string getTitle(string mid, string ParentID)
        {
            string title = "";
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@id", SqlDbType.NVarChar),
                    new SqlParameter("@ParentID", SqlDbType.NVarChar),
				};
                parameters[0].Value = mid;
                parameters[1].Value = ParentID;

                DataSet ds;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "cms_Messages$getTitle", parameters);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    title = ds.Tables[0].Rows[0]["title"].ToString();
                }

                return title;

            }
            catch (Exception ex)
            {
                return title;
            }
        }


        public static void Messages_SetRelateBatch(string mids,int persionid,  int type)
        {
            try
            {
                SqlParameter[] parameters = 
			    { 
                    new SqlParameter("@id1s", SqlDbType.NVarChar),
                    new SqlParameter("@id2", SqlDbType.Int),
                    new SqlParameter("@type", SqlDbType.Int),
				};
                parameters[0].Value = mids;
                parameters[1].Value = persionid;
                parameters[2].Value = type;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.ConnStr, CommandType.StoredProcedure, "cms_Messages$SetRelateBatch", parameters);
            }
            catch (Exception ex)
            {
                VatLid.DAL.ExceptionProcess(ex);
            }
        }      

        #endregion



        public static string getNiceUrl(Object objurl)
        {
            try
            {
                String url = objurl.ToString();
                String niceurl = "";

                niceurl = CleanString(url);
                niceurl = StripTags(niceurl);
                niceurl = ConvertVietnameseCharacterToEN(niceurl);
                niceurl = niceurl.ToLower();

                niceurl = niceurl.Replace(" ", "-");
                niceurl = niceurl.Replace("---", "-");
                niceurl = niceurl.Replace("--", "-");
                niceurl = niceurl.Replace("uy", "di");

                return niceurl;
            }
            catch
            {
                return "page";
            }
        }

        public static string TrimCharSpec(object input)
        {
            string _input = "";
            try
            {
                _input = (string)input;
                _input = _input.Replace("'", "\"");
            }
            catch { };

            return _input;
        }

        public static string StripTags(Object data)
        {
            String html = data as String;
            string pattern = @"<(.|\n)*?>";
            return Regex.Replace(html, pattern, string.Empty);
        }

        public static string CleanString(string strIn)
        {
            // Replace invalid characters with empty strings.k
            return Regex.Replace(strIn, @"[^\w\s\-]", "");
        }

        public static string ConvertVietnameseCharacterToEN(string sCharacter)
        {
            string sTemplate = "ĂẮẰẲẴẶăắằẳẵặÂẤẦẨẪẬâấầẩẫậÁÀẢÃẠáàảãạÔỐỒỔỖỘôốồổỗộƠỚỜỞỠỢơớờởỡợÓÒỎÕỌóòỏõọĐđÊẾỀỂỄỆêếềểễệÉÈẺẼẸéèẻẽẹƯỨỪỬỮỰưứừửữựÚÙỦŨỤúùủũụÍÌỈĨỊíìỉĩịÝỲỶỸỴýỳỷỹỵ";
            string sReplate = "AAAAAAaaaaaaAAAAAAaaaaaaAAAAAaaaaaOOOOOOooooooOOOOOOooooooOOOOOoooooDdEEEEEEeeeeeeEEEEEeeeeeUUUUUUuuuuuuUUUUUuuuuuIIIIIiiiiiYYYYYyyyyy";
            char[] arrChar = sTemplate.ToCharArray();
            char[] arrReChar = sReplate.ToCharArray();
            string sResult = "";//sCharacter;
            char digit;

            for (int ch = 0; ch < sCharacter.Length; ch++)
            {
                digit = Convert.ToChar(sCharacter.Substring(ch, 1));//arrChar[ch].ToString();;
                for (int i = 0; i < arrChar.Length; i++)
                    if (digit.Equals(arrChar[i]))
                        digit = arrReChar[i];
                sResult += digit;
            }       
            return sResult;
        }


        public static void setIsOpen(string mids, int userid)
        {
            try
            {
                SqlParameter[] parameters = { 
		            new SqlParameter("@mids", SqlDbType.NVarChar),	
			        new SqlParameter("@Posted", SqlDbType.Int),																																		
		        };
                parameters[0].Value = mids;
                parameters[1].Value = userid;

                VatLid.SqlHelper.ExecuteNonQuery(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "cms_Messages_isOpen$InsertBatch", parameters);
            }
            catch (Exception ex)
            {
            }
        }

       
    }


}
